package sanitycheck;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;

import setting.BioNLPSettings;
import util.io.FileUtil;
import def.BioNLPDocument;
import def.Protein;
import exp.Count;

public class SimpleFix {
	public static void main(String[] args){
		BioNLPSettings.init(args[0]);
		BioNLPSettings.print();
		Count sum = new Count();
		String path  =BioNLPSettings.getValue("dataPath");
		//			BioNLPSettings.parsePath = BioNLPSettings.trainParsePath;
		for (String filename :  new File(path).list()){
			//						String filename = "9825820.txt";
			if (filename.endsWith(".txt")){
				//					if (r.nextDouble()> 0.1)
				//						continue;
				String filePrefix = filename.replace(".txt", "");
				System.out.println(filename+ " to be processed");
				sum.add(processDocument(path, filePrefix));
			}
		}
	}

	private static Count processDocument(String path, String filePrefix) {
		Count c = new Count();
		BioNLPDocument doc = new BioNLPDocument(path, filePrefix);
		
		Hashtable<String, Protein> corefProteins = getCorefProteins(doc);
		System.err.println("[SIMPLEFIX] "+filePrefix+" MY "+corefProteins);
		System.err.println("[SIMPLEFIX] TRUTH "+doc.equiv);
		return c;
	}

	public static Hashtable<String, Protein> getCorefProteins(BioNLPDocument doc){
		ArrayList<Protein> proteins = new ArrayList<Protein>(doc.proteins);
		Collections.sort(proteins, new Comparator<Protein>(){
			@Override
			public int compare(Protein arg0, Protein arg1) {
				return arg0.tspan.startIdx - arg1.tspan.startIdx;
			}
		});

		Hashtable<String, Protein> corefProteins = new Hashtable<String,Protein>();
		if (proteins.size()>1){
			for (int i = 0; i < proteins.size() -1; i++){
				String dist = doc.text.text.substring(proteins.get(i).tspan.endIdx, proteins.get(i+1).tspan.startIdx);
				if (/*proteins.get(i).tspan.endIdx+4 >= proteins.get(i+1).tspan.startIdx
						&&*/ (dist.replace("[corrected]", "").trim().equals("(")
							&& doc.text.text.charAt(proteins.get(i+1).tspan.endIdx) == ')') || dist.matches("\\s+")){
					if (proteins.get(i).tspan.endIdx-proteins.get(i).tspan.startIdx > 
					proteins.get(i+1).tspan.endIdx - proteins.get(i+1).tspan.startIdx){
						corefProteins.put(proteins.get(i).tspan.tid, proteins.get(i+1));
					}
					else{
						corefProteins.put(proteins.get(i+1).tspan.tid, proteins.get(i+1));
					}
					i++;
				}
			}
		}
		System.err.println("[COREF_PROTEINS] from "+proteins);
		System.err.println("[COREF_PROTEINS] found "+corefProteins);
		return corefProteins;
	}
	
	/**
	 * test if P1-P2 should be with one single event
	 * failed
	 * @param path
	 * @param filePrefix
	 * @return
	 */
	private static Count processDocument2(String path, String filePrefix) {
		Count c = new Count();
		BioNLPDocument doc = new BioNLPDocument(path, filePrefix);
		
		String predPath = BioNLPSettings.getValue("PRED_DIR");
		String predFile = predPath + filePrefix + BioNLPSettings.getValue("EventAnnotationSuffix");
		
		
		String[] lines = FileUtil.getTextFromFile(predFile).split("\n");
		Hashtable<String, ArrayList<String>> triggerToArgs = new Hashtable<String, ArrayList<String>>();
		for (int i = 0; i < lines.length; i++){
			if (lines[i].startsWith("E")){
				if (lines[i].contains("Binding:") && !lines[i].contains("Theme2")){
					String tid = lines[i].substring(lines[i].indexOf(":")+1, lines[i].indexOf("Theme") -1).trim();
					String aid = lines[i].substring(lines[i].lastIndexOf(":")+1).trim();
					if (!triggerToArgs.containsKey(tid))
						triggerToArgs.put(tid, new ArrayList<String>());
					triggerToArgs.get(tid).add(aid);
				}
			}
		}
		for (String key:triggerToArgs.keySet()){
			ArrayList<String> list = triggerToArgs.get(key);
			if (list.size() != 2){
				System.err.println("[SIMPLEFIX] not 2 p-p @"+filePrefix+" , "+key+":" + list);
				continue;
			}
			Collections.sort(list, new Comparator<String>(){
				@Override
				public int compare(String o1, String o2) {
					return Integer.parseInt(o1.substring(1)) - Integer.parseInt(o2.substring(1));
				}
			});
			if (doc.tspans.get(list.get(0)).tspan.endIdx+1 == doc.tspans.get(list.get(1)).tspan.startIdx){
				System.err.println("[SIMPLEFIX] p-p @"+filePrefix+" , FOUND "+key+":" + doc.tspans.get(list.get(0)) +";;;"+doc.tspans.get(list.get(1)));
			}
			else{
				int dist = doc.tspans.get(list.get(1)).tspan.startIdx - doc.tspans.get(list.get(0)).tspan.endIdx;
				System.err.println("[SIMPLEFIX] p-p @"+filePrefix+" , NOT FOUND dist = "+dist+" "+key+":" + doc.tspans.get(list.get(0)) +";;;"+doc.tspans.get(list.get(1)));
			}
		}
		
		return c;
	}
	
	
	/**
	 * test if "interaction" always has two arguments as bindings.
	 * failed
	 * @param path
	 * @param filePrefix
	 * @return
	 */
	private static Count processDocument1(String path, String filePrefix) {
		Count c = new Count();
		BioNLPDocument doc = new BioNLPDocument(path, filePrefix);
		
		String predPath = BioNLPSettings.getValue("PRED_DIR");
		String predFile = predPath + filePrefix + BioNLPSettings.getValue("EventAnnotationSuffix");
		
		
		String[] lines = FileUtil.getTextFromFile(predFile).split("\n");
		ArrayList<String> list = new ArrayList<String>(), strings = new ArrayList<String>(); 
		for (int i = 0; i < lines.length; i++){
			if (lines[i].startsWith("T")){
				String str = lines[i].substring(lines[i].lastIndexOf("\t")+1);
				if (str.startsWith("interact")){
					list.add(lines[i].substring(0, lines[i].indexOf("\t")));
					strings.add(lines[i].substring(lines[i].lastIndexOf("\t")+1));
//					System.err.println("[SIMPLEFIX] interact @" + filePrefix +" "+lines[i]);
				}
			}
			else if (lines[i].startsWith("E")){
				for (int j = 0; j < list.size(); j++){
					String id = list.get(j);
					String str = strings.get(j);
					if (lines[i].contains("Binding:"+id+" ")){
						System.err.println("[SIMPLEFIX] {"+str+"}events @" + filePrefix +" "+lines[i]);
					}
				}
			}
		}
		
		
		
		
		if (!doc.valid){
			return c;
		}
		
		return c;
	}
}
